package cn.yuyiling.jelly.qa.controller;

import cn.yuyiling.jelly.qa.api.AnswerService;
import cn.yuyiling.jelly.qa.dto.AnswerDTO;
import cn.yuyiling.jelly.qa.mongodb.entity.Answer;
import cn.yuyiling.jelly.qa.mongodb.entity.Question;
import cn.yuyiling.jelly.sr.api.RankService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/answers")
public class AnswerController {

    private static final Logger logger = LoggerFactory.getLogger(AnswerController.class);
    @DubboReference(scope = "remote")
    private AnswerService answerService;

    @PutMapping("/create/{questionId}")
    public Answer createAnswer(@PathVariable String questionId, @RequestBody Answer answer) {
        return answerService.createAnswer(questionId, answer);
    }

    @PutMapping("/like/{id}")
    public Answer likeAnswer(@PathVariable String id) {
        return answerService.likeAnswer(id);
    }

    @PutMapping("/dislike/{id}")
    public Answer dislikeAnswer(@PathVariable String id) {
        return answerService.dislikeAnswer(id);
    }

    @PutMapping("/update/{id}")
    public Answer updateAnswer(@PathVariable String id, @RequestBody Answer answer) {
        return answerService.updateAnswer(id, answer);
    }

    @DeleteMapping("/{id}")
    public void deleteAnswer(@PathVariable String id) {
        answerService.deleteAnswerAndRelatedData(id);
    }

    @GetMapping("/top5HighLiked")
    public List<Answer> getTop5HighLikedAnswers() {
        return answerService.getTop5HighLikedAnswers();
    }

    @GetMapping("/{questionId}")
    public Answer getAnswerById(@PathVariable String id) {
        return answerService.getAnswerById(id);
    }


    @GetMapping("/view/{id}")
    public Answer viewAnswerById(@PathVariable String id) {
        logger.info("view Answer by ID: {}", id);
        return answerService.viewAnswerById(id);
    }

    @GetMapping("/view/top/{count}")
    public List<String> viewAnswerRank(@PathVariable Integer count) {
        logger.info("view Answer rank list top: {}", count);
        return answerService.get24HourTopViewAnswer(count);
    }

    /**
     * PB:
     * 注意在分布式部署的情况下，本代码可能被部署到多个节点（Pod），那么每个节点都会独立运行该定时任务，务必小心
     * 本示例多次执行该任务问题不大，如果存在多节点重复执行会有问题的情况下建议
     * 1）用redis加锁，避免多节点同时执行
     * 2）用其他定时任务机制保障该任务只被执行一次
     */
    //@Scheduled(cron = "0 0 * * * ?")
    @Scheduled(cron = "0/30 * * * * ?")
    public void refreshTop24hViewAnswerRanking() {
        answerService.refreshTop24hViewAnswerRanking();
    }

}